<?php

namespace app\admin\controller;

use app\admin\model\Paper;
use app\admin\model\TeacherModel;
use app\BaseController;
use app\lib\MiniWechat;

class Order extends BaseController
{
    /* 列表 */
    public function getList()
    {
        if (! $this->request->auth)
            return show(config('status.auth'), 'Authorization Failed');

        $page    = input('page', 1, 'intval');
        $perpage = 8;
        $where = [];
        $userId    = request()->post('user_id');
        $teacherId = request()->post('teacher_id');
        if (!empty($userId)) {
            $where[] = ['user_id', '=', $userId];
        }

        if (!empty($teacherId)) {
            $where[] = [
                'teacher_id', '=', $teacherId,
            ];
            $where[] = [
                'is_read', '=', 1
            ];
        }
        $model  = Paper::order('id desc')->with(['user'])->order('id desc')->append(['class_name']);
        if (!empty($where)) {
            $model->where($where);
            $total   = Paper::where($where)->where('is_pay',1)->count();
        } else {
            $total   = Paper::where('is_pay',1)->count();
        }

        $result = $model->where('is_pay',1)->page($page, $perpage)->select();
        foreach($result as $k=>$v){
            if(empty($v->student_comment)){
                $result[$k]->student_comment = 0;
            }else{
                $result[$k]->student_comment = 1;
            }
            if($v->teacher_id != 0){
                $Teacher = TeacherModel::where('id',$v->teacher_id)->find();
                if(!empty($Teacher)){
                    $result[$k]->teacher_name = $Teacher->name;
                }
            }

        }

        $data    = [
            'total' => $total, 'current' => $page, 'perpage' => $perpage, 'data' => $result
        ];
        return show(config('status.success'), 'success', $data);
    }


    /* 老师端论文列表 */
    public function getList2()
    {
        if (! $this->request->auth)
            return show(config('status.auth'), 'Authorization Failed');

        $page    = input('page', 1, 'intval');
        $perpage = 8;
        $where   = [];
        $userId  = request()->userinfo['id'];
        $status = request()->post('status');
        switch ($status) {
            case 1:
                $where[] = ['teacher_id', '=', 0];
                break;
            case 2:
                $where[] = ['teacher_id', '=', $userId];
                $where[] = ['is_read', '=', 0];
                break;
            case 3:
                $where[] = ['teacher_id', '=', $userId];
                $where[] = ['is_read', '=', 1];
                break;
        }

        $model  = Paper::order('id desc')->with(['user'])->order('id desc')->append(['class_name']);
        if (!empty($where)) {
            $model->where($where);
            $total = Paper::where($where)->where('is_pay',1)->count();
        } else {
            $total = Paper::where('is_pay',1)->count();
        }

        $result = $model->page($page, $perpage)->where('is_pay',1)->select();
        $data   = [
            'status'=>$status,'total' => $total, 'current' => $page, 'perpage' => $perpage, 'data' => $result
        ];
        return show(config('status.success'), 'success', $data);
    }

    /**
     * 获取文档链接
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function document()
    {
        $doc_id = input('id');

        $doc_url = Paper::where('id',$doc_id)->find();

        $doc_url->attr_files = explode(',', $doc_url->attr_files);
        $arr1 = [];
        foreach($doc_url->attr_files as $k=>$v){
            if($k != 0){
                array_push($arr1,$v);
            }
        }
        $doc_url->attr_files = $arr1;
        return show(config('status.success'), 'success', $doc_url['attr_files']);

    }

    public function receive()
    {
        if (! $this->request->auth)
            return show(config('status.auth'), 'Authorization Failed');

        $data = Paper::where('id',request()->post('id'))->update([
            'teacher_id' => $this->request->userinfo['id']
        ]);
        return show(config('status.success'), 'success', $data);
    }

    /* 详情 */
    public function detail()
    {
        if (! $this->request->auth)
            return show(config('status.auth'), 'Authorization Failed');

        $data = Paper::where('id',request()->post('id'))->append(['class_name'])->find();
        return show(config('status.success'), 'success', $data);
    }

    /* 更新 */
    public function update()
    {
        if (! $this->request->auth)
            return show(config('status.auth'), 'Authorization Failed');

        $data = Paper::where('id',request()->post('id'))->update([
            'score' => request()->post('score'),
            'is_read' => request()->post('is_read'),
            'teacher_comment' => request()->post('teacher_comment'),
        ]);
        if (request()->post('is_read')) {
            // 发送订阅消息
            $paper = Paper::find(request()->post('id'));
            $user = \app\admin\model\User::findOrEmpty($paper->user_id);
            if (!$user->isEmpty() && !empty($user->openid)) {
                $wechat = new MiniWechat();
                try {
                    $wechat->sendMsg([
                        'touser' => $user->openid, 'template_id' => 'MejL3RALtafqtd4MiBUquR2zldKORGyuMaeDNhex6os', 'data' => [
                            'thing1' => ['value' => $paper->title], 'phrase2' => ['value' => '已批阅'],
                        ]
                    ]);
                } catch (\Exception $e) {
                    return show(config('status.error'), '发送订阅消息失败：' . $e->getMessage());
                }
            }
        }
        return show(config('status.success'), 'success', $data);
    }
}